import { alert } from "./dialog.mjs";

export default function validate({
  container,
  valid,
  invalid,
  ignoreinsertrow = false,
  ignorewizardfinishstatus = false,
}) {
  if (container) {
    let result = [];
    container.querySelectorAll("input,textarea,select").forEach((element) => {
      if (element.validity.valid === false) {
        // console.log({ element, validity: element.validity });
        if (ignoreinsertrow && element.closest('tr[insertrow="true"]')) {
        } else if (
          ignorewizardfinishstatus &&
          element.name === "wizard_finishstatus"
        ) {
        } else
          result.push({
            name: element.name,
            message: element.validationMessage,
          });
      }
    });
    if (result.length > 0) {
      alert({
        table: {
          tr: [{ td: "[[name]]" }, { td: "[[message]]" }],
          data: result,
        },
      }).close(() => {
        if (invalid) invalid(result);
      });
    } else {
      // console.log({ result, valid, invalid });
      if (valid) valid();
    }
  }
}
